﻿///
/// Code taken from:
/// http://blog.waynehartman.com/articles/84.aspx
///
using System;
using System.Reflection;
using System.ComponentModel;

namespace Data.GameData.Utils
{
    public static class EnumUtils
    {
        /// <summary>
        /// Use reflection to access the DescriptionAttribute that specified when constructed the enum.  
        /// If the enum value doesn't have a DescriptionAttribute associated with it, return the ToString() value 
        /// of the enum itself.  That way, enums like 'Vanilla' get returned as "Vanilla" instead of null.
        /// </summary>
        /// <param name="value">The enum value to convert</param>
        /// <returns>The string representing the enum value</returns>
        public static string StringValueOf(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (attributes.Length > 0)
            {
                return attributes[0].Description;
            }
            else
            {
                return value.ToString();
            }
        }

        /// <summary>
        /// Calculate the enum value from a string value.  This uses the Enum static methods to compare the string value 
        /// to the list of enum values.  While this particular could be further optimized with caching, this sets up a 
        /// basic, but useful string value enumeration.
        /// </summary>
        /// <param name="value">The sttring to search for</param>
        /// <param name="enumType">The enum type to search in</param>
        /// <returns>The enum value as an object</returns>
        public static object EnumValueOf(string value, Type enumType)
        {
            string[] names = Enum.GetNames(enumType);
            foreach (string name in names)
            {
                if (StringValueOf((Enum)Enum.Parse(enumType, name)).Equals(value))
                {
                    return Enum.Parse(enumType, name);
                }
            }

            throw new ArgumentException("The string is not a description or value of the specified enum.");
        }
    }
}
